#!/usr/bin/env python

###########################################################################
# configure these paths:
LOGFILE = '/var/log/ovimclientd.log'
PIDFILE = '/var/run/ovimclientd.pid'

from OVIMClient import *
###########################################################################

import sys, os
import time

DBHOST = 'srvnas'
DBPORT = 'dbport'
DBUSER = 'OVIM'
DBPASSWD = 'OVIM123'

class Log:
    def __init__(self, f):
        self.f = f
    def write(self, s):
        self.f.write(s)
        self.f.flush()

def main():
    #change to data directory if needed
    os.chdir("/usr/local/bin/")
    #redirect outputs to a logfile
    sys.stdout = sys.stderr = Log(open(LOGFILE, 'a+'))
    #ensure the that the daemon runs a normal user
    os.setegid(0)     #set group first "pydaemon"
    os.seteuid(0)     #set user "pydaemon"
    #start the user program here:
    while True:
        client = OVIMClient(DBHOST, DBPORT, DBUSER, DBPASSWD)
        client.main()
        time.sleep(60)
        del client

if __name__ == "__main__":
    # do the UNIX double-fork magic, see Stevens' "Advanced
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    # decouple from parent environment
    os.chdir("/")   #don't prevent unmounting....
    os.setsid()
    os.umask(0)

    # do second fork
    try:
        pid = os.fork()
        if pid > 0:
            # exit from second parent, print eventual PID before
            #print "Daemon PID %d" % pid
            open(PIDFILE,'w').write("%d"%pid)
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    # start the daemon main loop
    main()
